package com.ttxs.common.security.util;


import com.ttxs.common.core.vo.LoginUser;
import com.ttxs.common.core.vo.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class AuthUtils {

    public static boolean isLogin(String token) {
        return TokenUtils.isLogin(token);
    }

    public static Token createToken(LoginUser loginUser) {
        return TokenUtils.createToken(loginUser);
    }

    /**
     * 兼容老系统的已经生成了的token
     * @param loginUser
     * @param rawToken
     * @return
     */
    @Deprecated
    public static Token createToken(LoginUser loginUser, String rawToken) {
        return TokenUtils.createToken(loginUser, rawToken);
    }


    public static LoginUser getLoginUser(String token) {
        return TokenUtils.getLoginUser(token);
    }

    public static boolean hasPerms(String url, String token) {
        LoginUser loginUser = TokenUtils.getLoginUser(token);
        List<String> urlPatterns = new ArrayList<>(loginUser.getUrlPatterns());
        return StringUtils.isMatch(urlPatterns, url);
    }

    public static void removeToken(String token) {
        TokenUtils.logout(token);
    }

    public static boolean isMatch(String pattern, String requestUrl) {
        return StringUtils.isMatch(pattern, requestUrl);
    }

    public static boolean isMatch(List<String> patternUrls, String requestUrl) {
        return StringUtils.isMatch(patternUrls, requestUrl);
    }

    @Slf4j
    private static class StringUtils {

        public static boolean isMatch(String pattern, String url) {
            return new AntPathMatcher().match(pattern, url);
        }

        public static boolean isMatch(List<String> patternUrls, String url) {
            if (!hasText(url) || isEmpty(patternUrls)) {
                return false;
            }
            if (log.isDebugEnabled()) {
                log.debug("patternUrls:{}", patternUrls);
            }
            for (String pattern : patternUrls) {
                if (isMatch(pattern, url)) {
                    if (log.isDebugEnabled()) {
                        log.debug("url:{}, pattern:{} is matched.", url, pattern);
                    }
                    return true;
                }
            }
            return false;
        }

        public static boolean hasText(String str) {
            return str != null && str.trim().length() > 0;
        }

        public static boolean isEmpty(Collection list) {
            return list == null || list.isEmpty();
        }
    }
}
